﻿using System;
using SaleManagement.Web.App_Code;
using SaleManagement.Domains;
using SaleManagement.Services;
using DevExpress.Web.ASPxGridView;
using System.Web.UI.HtmlControls;
using System.Data;

namespace SaleManagement.Web.Pages
{
  public partial class GuaranteeInfo : BasePage
  {
    #region Properties
    private string m_InnerError = string.Empty;
    private string m_InnerProperty = string.Empty;

    #endregion

    #region Events

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsCallback && !IsPostBack)
      {
        if (!string.IsNullOrEmpty(Request.QueryString["c"]))
        {
          txtProductCode.Text = Request.QueryString["c"];
        }

        LoadRepository();
        LoadGuaranteeList();
        btnSearch_OnClick(null, null);
      }
    }

    protected void btnSearch_OnClick(object sender, EventArgs e)
    {
      string code = txtProductCode.Text;
      if (string.IsNullOrEmpty(code.Trim())) return;
      DataSet ds = new PurchaseDetailService().GetInfoByCode(code.ToUpper());
      if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0) return;
      DataRow row = ds.Tables[0].Rows[0];
      lblCustomerCode.Text = row["CustomerNo"].ToString();
      lblClient.Text = row["CustomerName"].ToString();
      lblPurchaseDate.Text = row["PurchaseDate"].ToString();
      lblGuranteeDate.Text = row["GuaranteePeriod"].ToString();
      DateTime guaranteeDate = DateTime.Now.AddDays(-1);
      if (DateTime.TryParseExact(row["GuaranteePeriod"].ToString(), "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None, out guaranteeDate))
      {
        if (guaranteeDate >= DateTime.Now) lblIsRemainGuarantee.Text = "Còn bảo hành";
        else lblIsRemainGuarantee.Text = "Hết bảo hành";
      }
      else
      {
        lblIsRemainGuarantee.Text = "";
      }
      LoadGuaranteeList();
    }

    protected void gvGuarantee_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
      string para = e.Parameters;
      if (para == "Save")
      {
        m_InnerProperty = "Save";
        m_InnerError = SaveGuarantee();
      }
      LoadGuaranteeList();
    }

    protected void gvGuarantee_PageIndexChanged(object sender, EventArgs e)
    {
      LoadGuaranteeList();
    }

    protected void gvGuarantee_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_InnerError;
      e.Properties["cpInnerProperty"] = m_InnerProperty;
    }

    protected void gvGuarantee_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
    {
      if (e.DataColumn.Name == "Command")
      {
        ASPxGridView gvObject = sender as ASPxGridView;
        HtmlImage img = gvObject.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "imgEdit") as HtmlImage;
        if (img != null)
        {
          img.Attributes.Add("onclick", "fillWithInfo(" + e.VisibleIndex + ")");
        }
      }
    }
  
    #endregion

    #region Methods

    private void LoadRepository()
    {
      cbxRepository.DataSource = new RepositoryService().Search(StatusList.RepositoryType.GUARANTEE);
      cbxRepository.DataBind();
    }

    private void LoadGuaranteeList()
    {
      string code = txtProductCode.Text;
      if (string.IsNullOrEmpty(code.Trim())) return;
      gvGuarantee.DataSource = new GuaranteeService().GetByCode(code.ToUpper());
      gvGuarantee.DataBind();
    }

    private string SaveGuarantee()
    {
      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          string code = txtCode.Text.Trim();
          DataSet listPrevious = new PreviousPurchaseService().GetByCode(code.ToUpper() );
          if (listPrevious == null || listPrevious.Tables.Count == 0 || listPrevious.Tables[0].Rows.Count == 0)
          {
            return "Không tìm thấy mẫu bán hàng tương ứng";
          }

          Guarantee guarantee = null;
          if (!string.IsNullOrEmpty(hfGuaranteeId.Value))
          {
            int id = -1;
            int.TryParse(hfGuaranteeId.Value, out id);
            guarantee = new GuaranteeService().GetById(id);
            if (guarantee == null)
            {
              return "Không tìm thấy dữ liệu tương ứng";
            }
            guarantee.UpdatedBy = CurrentUser.Username;
            guarantee.UpdatedDate = DateTime.Now;
          }
          else
          {
            guarantee = new Guarantee();
            guarantee.CreatedBy = CurrentUser.Username;
            guarantee.CreatedDate = DateTime.Now;
            guarantee.UpdatedBy = CurrentUser.Username;
            guarantee.UpdatedDate = DateTime.Now;
          }
          guarantee.Code = txtCode.Text.Trim().ToUpper();

          guarantee.ReceiveDate = dexReceiveDate.Date;
          if (dexReturnDate.Date != DateTime.MinValue)
          {
            guarantee.ReturnDate = dexReturnDate.Date;
          }
          if (dexAttend.Date != DateTime.MinValue)
          {
            guarantee.AttendReturn = dexAttend.Date;
          }

          guarantee.RepositoryId = Convert.ToInt32(cbxRepository.Value);
          int oldChareFee = guarantee.ChargeFee;
          guarantee.ChargeFee = Convert.ToInt32(txtChargeFee.Text);
          guarantee.Notes = mmNote.Text;
          new GuaranteeService().Save(guarantee);

          int guaranteeListId = guarantee.GuanranteeListId;
          Domains.GuaranteeList guaranteeList = new GuaranteeListService().GetById(guaranteeListId);
          if (guaranteeList == null) return "Không tìm thấy mẫu hóa đơn bảo hành tương ứng";
          if (!guaranteeList.TotalFee.HasValue) guaranteeList.TotalFee = 0;
          guaranteeList.TotalFee = guaranteeList.TotalFee - oldChareFee + guarantee.ChargeFee;
          new GuaranteeListService().Save(guaranteeList);


          ConnectionScope.Complete();
          return string.Empty;
          
        }
      }
      catch (Exception ex)
      {
        WriteLog("GuaranteeInfo::Save Guarantee", ex);
        return "Có lỗi trong quá trình lưu dữ liệu";
      }
    }

    

    #endregion

  }
}
